﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{

    int score = 0;
    //上次获取输入的时间
    float nextTime;
    //每次获取输入的间隔时间，避免瞬间获取大量输入
    public float delay = 0.3f;
    Vector3 direct;
    Vector3 directEuler;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.W) && Time.time > nextTime)
        {
            nextTime = Time.time + delay;
            //Debug.Log("w");
            direct = new Vector3(0, 0, 1);
            directEuler = new Vector3(0, 180, 0);
            Move();
        }
        if (Input.GetKey(KeyCode.A) && Time.time > nextTime)
        {
            nextTime = Time.time + delay;
            //Debug.Log("a");
            direct = new Vector3(-1, 0, 0);
            directEuler = new Vector3(0, 90, 0);
            Move();
        }
        if (Input.GetKey(KeyCode.S) && Time.time > nextTime)
        {
            nextTime = Time.time + delay;
            direct = new Vector3(0, 0, -1);
            directEuler = new Vector3(0, 0, 0);
            Move();
        }
        if (Input.GetKey(KeyCode.D) && Time.time > nextTime)
        {
            nextTime = Time.time + delay;
            direct = new Vector3(1, 0, 0);
            directEuler = new Vector3(0, 270, 0);
            Move();
        }
    }

    //向移动方向移动一步
    void Move()
    {
        transform.LookAt(transform.position + direct);
        if (ValidAndMoveBox())
        {
            transform.Translate(transform.InverseTransformDirection(direct));
        }
    }

    //检查是否能移动，是否需要移动箱子
    bool ValidAndMoveBox()
    {
        RaycastHit hit;
        //1.判断移动方向前一格是否有碰撞体
        if (Physics.Raycast(transform.position, direct, out hit, 1f))
        {
            Debug.Log("y-"+hit.transform.name);
            //2.判断碰撞体是什么
            //3.碰撞体是墙
            if (hit.transform.tag == "wall")
            {
                return false;
            }
            //4.碰撞体是箱子
            if (hit.transform.tag == "box")
            {
                RaycastHit boxHit;
                //5.判断箱子的下一格是否有碰撞体
                if (Physics.Raycast(hit.transform.position, direct, out boxHit, 1f))
                {
                    //6.碰撞体只要不是目标就不移动
                    if (boxHit.transform.tag != "target")
                    {
                        return false;
                    }
                }
                hit.transform.position += direct;
            }
        }

        //其他情况可以移动
        return true;
    }
}
